// pages/device/device.js

const utils = require("../../utils/util.js")
const btUtils = require("../../utils/btUtils.js")

const SERVICE_UUID = "0000ffe0";
const CHARACTERISTIC_UUID = "0000ffe1";

var r_service_uuid;
var r_characteristic_uuid;
var r_characteristic_properties;
var deviceId;

//预设的固定操作的指令数据字符串
const READ_BATTERY = "5AA50481040186"
const READ_SYS_TIME = "5AA50481000485"

const WEEK_ARRAY = ["星期一", "星期二", "星期三", "星期四", "星期五", "星期六", "星期日"];

Page({
  /**
   * 页面的初始数据
   */
  data: {
    weekDays: WEEK_ARRAY,
    deviceId:'',
    deviceName: '',
    deviceBattery: '',
    deviceWeekDay: '选择星期',
    weekIndex: "",
    deviceTime: '选择时间'
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {

    console.log("options is:", options)
    deviceId = options.deviceId;
    this.setData({
      deviceId: deviceId
    });

    //监听重连
    wx.onBLEConnectionStateChange(function (deviceId, conneted) {

      var thisPage = this 

      if (conneted) {
        return
      }

      wx.createBLEConnection({
        deviceId: deviceId,
        success: res => {
          console.log("设备已经重新连接");
        }
      })
    });

    //遍历服务，找到想要的服务
    //在遍历特征，找到想要的特征
    wx.getBLEDeviceServices({
      deviceId: deviceId,
      success: function (res, errMsg){
        if (!res.services || res.services.length == 0){
          wx.showToast({
            title: 'services 为空',
          })
        }

        console.log("发现服务：", res)
        for (var service of res.services){
          if (service.uuid && service.uuid.toLowerCase().indexOf(SERVICE_UUID) == 0){
            r_service_uuid = service.uuid;

            console.log("已发现服务：" + SERVICE_UUID)

            //遍历特征
            wx.getBLEDeviceCharacteristics({
              deviceId: deviceId,
              serviceId: r_service_uuid,
              success: function (res, msg){
                if (res.characteristics || res.characteristics.length != 0) {
                 
                  console.log("特征：", res)
                  for(var char of res.characteristics){
                    if (char.uuid.toLowerCase().indexOf(CHARACTERISTIC_UUID) == 0){
                      r_characteristic_uuid = char.uuid
                      r_characteristic_properties = char.propertices;

                      console.log("已发现特征：" + CHARACTERISTIC_UUID);

                      //绑定监听
                      //thisPage.lisentCharateristicValue();
                      //启用监听功能,不启用收不到变化
                      wx.notifyBLECharacteristicValueChange({
                        deviceId: deviceId,
                        serviceId: r_service_uuid,
                        characteristicId: r_characteristic_uuid,
                        state: true,
                        success: function (msg) {
                          console.log("设备监听开启成功")
                          wx.showToast({
                            title: '设备连接成功!',
                          })
                        },
                        fail: function (msg) {
                          wx.showToast({
                            title: '开启监听设备特征值失败' + msg
                          })
                        }
                      });
                      break
                    }
                  }
                }
              },
              fail: function(msg){
                console.log('发现特征失败:' + msg)
                wx.showToast({
                  title: '发现特征失败:' + msg
                })
              }
            })

            break;
          }
        }
      },
      fail: function(errorMsg){
        console.log('读取服务失败:' + errorMsg)
        wx.showToast({
          title: '读取服务失败' + errorMsg
        })
      }
    })
  },
  onShow: function(){
    this.lisentCharateristicValue();
  },
  onHide: function(){

  },
  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    //断开连接
    wx.closeBLEConnection({
      deviceId: deviceId,
      success: function(){
        wx.showToast({
          title: '已与设备断开连接'
        })
      }
    })
  },
  lisentCharateristicValue: function(){

    //搞个事件总线 eventBUs, 解决多个界面去绑定蓝牙监听的问题
    var page = this;
    //监听特征值， 必须启用监听功能才能收到变化
    //res 中 deviceId, serviceId, characteristicId, value
    wx.onBLECharacteristicValueChange(function (res){

      console.log("in device.js,res is :", res);

      //先判断是不是 OK, 判断长度
      if (res.value.byteLength <= 4){
        var str = utils.ab2str(res.value);
        console.log("转换成字符串是:" + str);
        wx.showToast({
          title: '操作成功:' + str,
        })
        return;
      }

      var hex = utils.ab2hex(res.value);
      console.log("接收到的数据是:", hex);

      var data = btUtils.parseHex(hex)
      
      if(!data){
        console.log("数据解析失败:" + hex);
        wx.showToast({
          title: '数据解析失败!',
        })
        return
      }

      console.log("解析出来的数据是：", data)

      //获取电量
      if (data.address_hex = "04" && data.dataArray.length == 1){
        var battery = parseInt(data.dataArray[0], 16);
        page.setData({
          deviceBattery: battery
        })
      } else if (data.address_hex = "00" && data.dataArray.length == 4){  //系统时间
        //00 时， 01分， 03秒
        let hour = parseInt(data.dataArray[0], 16)
        let minute = parseInt(data.dataArray[1], 16)
        let second = parseInt(data.dataArray[2], 16)
        let week = parseInt(data.dataArray[3], 16)

        page.setData({
          deviceTime: hour + ":" + minute + ":" + second,
          deviceWeekDay: WEEK_ARRAY[week - 1],
          weekIndex: week - 1
        })
      }
    });
  },
  /**
   * 获取电量 04_01
   */
  getBarrery: function(){

    wx.showLoading({
      title: '读取电量中..',
    })
    var value = utils.hex2ab(READ_BATTERY);
    wx.writeBLECharacteristicValue({
      deviceId: deviceId,
      serviceId: r_service_uuid,
      characteristicId: r_characteristic_uuid,
      value: value,
      success: function (errMsg) {
        wx.hideLoading()
        wx.showToast({
          title: '请求成功!：' + errMsg,
        })
      },
      fail: function (errMsg) {
        wx.hideLoading()
        wx.showToast({
          title: '失败：' + errMsg,
        })
      }
    })
  },

  /**
   * 写入系统时间 00_04
   */
  writeDeviceTime: function(){

    wx.showLoading({
      title: '写入设备时间中..',
    })

    //根据当前选择的时段确定访问地址
    let address = "00";  //

    //获取各项数据，生成
    var dataArry = []   //4 length

    let timeArray = this.data.deviceTime.split(":")
    if(timeArray.length == 1){
      wx.showToast({
        title: '请选择时间'
      })
      return
    }

    console.log("deviceTime is：", this.data.deviceTime);
    console.log("array is：", timeArray);

    let hour_hex = utils.intTo2Hex(parseInt(timeArray[0]))
    let minute_hex = utils.intTo2Hex(parseInt(timeArray[1]))
    let second_hex = utils.intTo2Hex(parseInt(timeArray[2]))
    
    //星期
    if(!this.data.weekIndex){
      wx.showToast({
        title: '请选择星期',
      })
      return;
    }

    let week_hex = utils.intTo2Hex((this.data.weekIndex + 1))

    let dataArray = []
    dataArray.push(hour_hex)
    dataArray.push(minute_hex)
    dataArray.push(second_hex)
    dataArray.push(week_hex)

    let str = btUtils.encodeWritte(address, dataArray);

    console.log("编码完成的数据是 : " + str)

    var value = utils.hex2ab(str);

    wx.writeBLECharacteristicValue({
      deviceId: deviceId,
      serviceId: r_service_uuid,
      characteristicId: r_characteristic_uuid,
      value: value,
      success: function (errMsg) {
        wx.hideLoading();
        //console.log("设置时间请求写入成功:", dataArray)
      },
      fail: function (errMsg) {
        wx.hideLoading();
        wx.showToast({
          title: '数据访问请求写入失败：' + errMsg,
        })
      }
    })
  },
  /**
   * 读取设备时间 00_04
   */
  readDeviceTime: function(){

    wx.showLoading({
      title: '读取设备时间中..',
    })

    var value = utils.hex2ab(READ_SYS_TIME);

    wx.writeBLECharacteristicValue({
      deviceId: deviceId,
      serviceId: r_service_uuid,
      characteristicId: r_characteristic_uuid,
      value: value,
      success: function (errMsg) {
        wx.hideLoading()
        wx.showToast({
          title: '请求成功' + errMsg,
        })
      },
      fail: function (errMsg) {
        wx.hideLoading()
        wx.showToast({
          title: '数据访问请求写入失败：' + errMsg,
        })
      }
    })
  },
  /**
   * 跳转至设置是时间段界面
   */
  setPeriod: function(){
    wx.navigateTo({
      url: '../intervalSetting/intervalSetting?suuid=' + r_service_uuid + "&cuuid=" + r_characteristic_uuid + "&deviceId=" + deviceId,
    })
  },
  onWeekPeckerSelect: function(e){
    console.log(e);
    let weekIndex = parseInt(e.detail.value)

    this.setData({
      deviceWeekDay: WEEK_ARRAY[weekIndex],
      weekIndex: weekIndex
    })
  },
  onTimePeckerSelect: function (e) {
    console.log(e);
    
    let time = e.detail.value + ":00"
    this.setData({
      deviceTime: time
    })
  }
})
